<template>
  <div class="box">
    <el-row style="border:0px solid red;width:90%;margin:0 auto;">
      <el-col>
        <div style="float: right;margin-top: 20px;">
          <el-button type="primary" size="small" @click="openUpdatePwd">修改密码</el-button>
          <el-button type="primary" size="small" @click="editPeopleInfo">编辑</el-button>
          <el-button size="small" @click="back">返回</el-button>
        </div>
      </el-col>
      <el-col>
        <el-row style="border-bottom:1px solid #E9EEF3;height: 187px;">
          <el-col :span="5" >
            <div class="contentimg">
                   <span class="img_content">
                       <a  target="view_frame">
                       <img :src="emp.empImgpath" alt="">
                       <span class="mask" @click="clickChange">点击更换头像  </span></a>
                   </span>
            </div>

          </el-col>
          <el-col :span="16" style="margin-left: 40px;">
            <p style="font-size: 29px;margin-top: 60px;">{{emp.empName}}</p>
            <p style="margin-top: 10px;font-size:12px;color: #777;">
              <span>部门:{{emp.deptByDeptsId.deptName}}</span>
              <span style="margin-left: 19px;">职位:{{emp.positionList[0].postName}}</span>
            </p>
          </el-col>
        </el-row>
        <el-row style="margin-top: 10px;">
          <el-col>
            <div class="info">基础资料</div>
          </el-col>
          <el-form label-width="100px" class="empFrom" :label-position="'left'">
            <el-row style="margin-left: 86px;">
              <el-col :span="10">
                <el-form-item label="用户名">
                  <span class="infoSpan">{{emp.empName}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别">
                  <span class="infoSpan">{{emp.empSex}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="联系电话">
                  <span class="infoSpan">{{emp.empPhone}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入职日期">
                  <span class="infoSpan">{{emp.dateEntry}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="部门">
                  <span class="infoSpan">{{emp.deptByDeptsId.deptName}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位">
                  <span class="infoSpan">{{emp.positionList[0].postName}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="工龄">
                  <span class="infoSpan">{{workingYears}}</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="地址">
                  <span class="infoSpan">{{emp.empAddressProvince}}{{emp.empAddressCity}}{{emp.empAddressArea}}{{emp.empAddressDetailed}}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-row>
      </el-col>
    </el-row>
    <!--编辑头像-->
    <el-dialog
      title="编辑头像"
      :visible.sync="headerImage">
        <span>
        <el-row>
          <input type="file" id="uploads" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event,1)"
                 class="el-button" style="width: 300px;margin-bottom:15px;">
        </el-row>
        <el-row :gutter="10">
          <el-col :span="14">
            <!-- 裁剪 -->
              <vueCropper
                style="width:100%;height:300px"
                ref="cropper"
                :img="attach.customaryUrl"
                :autoCrop="options.autoCrop"
                :fixedBox="options.fixedBox"
                :canMoveBox="options.canMoveBox"
                :autoCropWidth="options.autoCropWidth"
                :autoCropHeight="options.autoCropHeight"
                :centerBox="options.centerBox"
                @realTime="realTime"
              >
              </vueCropper>
          </el-col>
          <el-col :span="10">
            <h2 align="center">头像预览</h2>
            <div class="show-preview">
              <div :style="previews.div" class="preview">
                <img :src="previews.url" :style="previews.img">
              </div>
            </div>
          </el-col>
        </el-row>
      </span>
      <span slot="footer" class="dialog-footer">
           <el-button @click="headerImage = false">取 消</el-button>
        <el-button type="primary" @click="cut('blob')">确 定</el-button>
      </span>
    </el-dialog>
    <!--修改密码-->
    <el-dialog
      title="修改密码"
      width="38%"
      :visible.sync="dialogPwd" top="18vh">
      <el-form  :model="empPwd" :rules="empPwdRules" ref="ruleForm" label-width="100px" style="margin-top: 12px;">
        <el-form-item label="旧密码" prop="oldPwd">
          <el-input type="password"  v-model="empPwd.oldPwd" autocomplete="off" style="width: 305px;" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码:" prop="newPwd">
          <el-input type="password"  v-model="empPwd.newPwd" autocomplete="off" style="width: 305px;" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码:" prop="confirmPwd">
          <el-input type="password" v-model="empPwd.confirmPwd" autocomplete="off" style="width: 305px;" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePwd">确定</el-button>
          <el-button @click="resetForm('ruleForm')">重置表单</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--编辑用户信息弹框-->
    <el-dialog
      title="编辑个人信息"
      :visible.sync="dialogVisible" top="18vh"
      width="31%">
      <el-form :model="updateInfo" label-width="90px" :label-position="'left'" ref="updateInfoFrom" style="margin-left: 10px;" :rules="updateInfoRules">
        <el-form-item label="联系电话:" prop="empPhone">
          <el-input style="width:250px;" v-model="updateInfo.empPhone"></el-input>
        </el-form-item>
        <el-form-item label="地址:" prop="empAddressArea">
          <v-distpicker
            :province="updateInfo.empAddressProvince" @province="ChangeProvince"
            :city="updateInfo.empAddressCity" @city="ChangeCity"
            :area="updateInfo.empAddressArea" @area="ChangeArea"
            class="distpicker-address-wrapper"></v-distpicker>
        </el-form-item>
        <el-form-item label="详细地址:" prop="empAddressDetailed">
          <el-input style="width:250px;" v-model="updateInfo.empAddressDetailed"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import VDistpicker from 'v-distpicker'
  import AesUtil from '../assets/aes-util';

  export default {
    inject:['reload'],
    components: {VDistpicker},
    data() {
      var yzOldPwd = (rule, value, callback) => {
        this.$axios.get("http://localhost:8088/user/yzPwd",
          {
            params: {
              employeesId: JSON.parse(sessionStorage.getItem("user")).employeesId,
              oldPwd: AesUtil.set(value)
            }
          }).then(v => {
          if (v.data == 0) {
            callback(new Error('旧密码错误'));
          } else if (v.data == 1) {
            callback();
          }
        }).catch()

      };

      var validatePass1 = (rule, value, callback) => {
        if (value == this.empPwd.oldPwd) {
          callback(new Error('旧密码和新密码一致'));
        } else {
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value !== this.empPwd.confirmPwd) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      };
      var checkedPhone = (rule, value, callback) => {
        if(this.updateEmpphone==value){
          callback();
        }else{
          this.$axios.get("http://localhost:8088/emp/emp_phone",
            {params:{
                phone:value
              }}).then(v=>{
            if(v.data == 1){
              callback(new Error('联系电话重复'));
            }else{
              callback();
            }
          }).catch();
        }
      };
      return {
        headerImage: false,//更换头像
        dialogVisible: false,
        dialogPwd: false,
        updateEmpphone:'',
        emp: {
          employeesId: '',
          empName: '',
          empSex: '',
          empPhone: '',
          empAddressProvince: '',
          empAddressCity: '',
          empAddressArea: '',
          empAddressDetailed: '',
          dateEntry: '',
          empImgpath: '',
          deptByDeptsId: {
            deptsId: '',
            deptName: '',
          },
          positionList: [
            {
              postId: '',
              postName: '',
            }
          ],

        },
        empPwd: {
          oldPwd: '',
          newPwd: '',
          confirmPwd: ''
        },
        empPwdRules: {
          oldPwd: [
            {required: true, message: '请输入旧密码', trigger: 'blur'},
            {validator: yzOldPwd, trigger: 'blur'}
          ],
          newPwd: [
            {required: true, message: '请输入新密码密码', trigger: 'blur'},
            {validator: validatePass1, trigger: 'blur'}
          ],
          confirmPwd: [
            {required: true, message: '请输入确认密码', trigger: 'blur'},
            {validator: validatePass2, trigger: 'blur'}

          ],
        },
        //修改部门信息
        updateInfo: {
          employeesId: '',
          empPhone: '',
          empAddressProvince: '',
          empAddressCity: '',
          empAddressArea: '',
          empAddressDetailed: '',
        },
        updateInfoRules: {
          empPhone: [
            {required: true, message: '联系电话不能为空', trigger: 'blur'},
            {pattern: /^1[3456789]\d{9}$/, message: '联系电话号码格式错误'},
            { validator:checkedPhone,trigger: 'blur' }
          ],
          empAddressDetailed:[
            {required: true,message: '详细地址不能为空！',trigger: 'change'}
          ],
          empAddressArea:[
            {required: true,message: '地址不能为空！',trigger: 'change'}
          ],
        },
        fullscreenLoading: false,//loading
        options: {
          autoCrop: true, //默认生成截图框
          fixedBox: false, //固定截图框大小
          canMoveBox: false, //截图框不能拖动
          autoCropWidth: 200, //截图框宽度
          autoCropHeight: 200, //截图框高度
          centerBox: false, //截图框被限制在图片里面
        },
        previews: {
          div: null,
          url: null,
          img: null
        }, //实时预览图数据
        attach: { //后端附件表
          user: null,
          customaryUrl: '', //原图片路径
          laterUrl: '', //裁剪后图片路径  /static/logo.png
          attachType: 'photo', //附件类型
        },
      }
    },
    created() {
      this.obtainUserInfo(JSON.parse(sessionStorage.getItem("user")).employeesId)
    },
    methods: {
      //返回上一页
      back() {
        this.$router.go(-1);//返回上一层
      },
      //获取当前用户的信息
      obtainUserInfo(employeesId) {
        this.$axios.get("http://localhost:8088/user/personal",
          {
            params: {
              employeesId: employeesId
            }
          }).then(v => {
          this.emp = v.data;
        }).catch();
      },
      //打开修改密码弹框
      openUpdatePwd() {
        if (this.$refs.ruleForm != undefined) {
          this.$refs.ruleForm.resetFields();
        }
        this.dialogPwd = true;
      },
      //修改密码
      updatePwd() {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            this.$axios.post("http://localhost:8088/user/updatePwd",
              this.qs.stringify({
                employeesId: JSON.parse(sessionStorage.getItem("user")).employeesId,
                newPwd: AesUtil.set(this.empPwd.confirmPwd)
              })).then(() => {
              this.dialogPwd = false;
              this.$refs.ruleForm.resetFields();
              //loading
              this.openFullScreen2();
              setTimeout(() => {
                this.backLogin()
              }, 3000);
            }).catch();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },

      openFullScreen2() {
        const loading = this.$loading({
          lock: true,
          text: '即将跳转到登录...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        setTimeout(() => {
          loading.close();
        }, 3000);
      },
      //返回登录页面
      backLogin() {
        //重置密码成功之后，身份过期，返回到登录页面
        this.$axios.post("http://localhost:8088/user/login_out").then(() => {
          sessionStorage.clear();//清除用户信息
          localStorage.clear();//清除用户信息
          this.$router.push('/login');
          //退出登录 禁止浏览器后退
          history.pushState(null, null, document.URL);
          window.addEventListener("popstate", function (e) {
            history.pushState(null, null, document.URL);
          }, false);
        }).catch();
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //编辑个人信息弹框
      editPeopleInfo() {
        this.updateInfo = {
          employeesId: '',
          empPhone: '',
          empAddressProvince: '',
          empAddressCity: '',
          empAddressArea: '',
          empAddressDetailed: '',
        },
          this.updateEmpphone =  this.emp.empPhone;
          //赋值
          this.updateInfo.employeesId = this.emp.employeesId;
        this.updateInfo.empPhone = this.emp.empPhone;
        this.updateInfo.empAddressProvince = this.emp.empAddressProvince;
        this.updateInfo.empAddressCity = this.emp.empAddressCity;
        this.updateInfo.empAddressArea = this.emp.empAddressArea;
        this.updateInfo.empAddressDetailed = this.emp.empAddressDetailed;
        this.dialogVisible = true;
      },
      ChangeProvince(v) {
        this.updateInfo.empAddressProvince = v.value;
      },
      ChangeCity(v) {
        this.updateInfo.empAddressCity = v.value;
      },
      ChangeArea(v) {
        this.updateInfo.empAddressArea = v.value;
      },
      //修改个人信息确定
      updateOk() {
        this.$refs.updateInfoFrom.validate((valid) => {
          if (valid) {
            this.$axios.post("http://localhost:8088/user/update_some_info", this.updateInfo).then(() => {
              this.dialogVisible = false;
              this.obtainUserInfo(this.emp.employeesId);
            }).catch();
          } else {
            console.log('error submit!!');
            return false;
          }
        });

      },
      //头像上传部分
      //点击更换 出现编辑头像弹框
      clickChange(){
        this.attach.customaryUrl = this.emp.empImgpath;
        this.headerImage=true;
      },

      //实时预览
      realTime(data) {
        this.previews = data
      },
      //选择本地图片
      uploadImg(e, num) {
        var file = e.target.files[0];
        if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
          this.$message.error('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');
          return false;
        }
        //fileReader 接口，用于异步读取文件数据
        var reader = new FileReader();
        reader.readAsDataURL(file); //重要 以dataURL形式读取文件
        reader.onload = e => {
          let data = e.target.result
          this.attach.customaryUrl = data
        }
      },
      //确认截图,上传
      cut(type) {
        if (this.attach.customaryUrl !== '' && this.attach.customaryUrl != null) {
          var formData = new FormData();
          this.$refs.cropper.getCropBlob(res => {
            //res是裁剪后图片的bolb对象
            formData.append("file", res,this.emp.employeesId);
            console.log(res);
            //传到后台进行上传
            this.$axios.post("http://localhost:8088/upload",formData).then(v=>{
              //关闭弹框
              this.headerImage = false;
              //重新存头像途径
              sessionStorage.setItem('empImagePath', JSON.stringify(v.data));
              //刷新
              this.reload();
            }).catch();

          })
        } else {
          this.$message({
            message: '请先选择图片！',
            duration: 2000,
            type: 'warning'
          });
        }
      }
    },
    computed: {
      workingYears() {
        return dateSubMonth(this.emp.dateEntry);
      }
    }
  }

  //计算工龄
  function dateSubMonth(date) {
    var date1 = new Date(date);
    var date2 = new Date();
    var monthCount = parseInt(date2.getFullYear() - date1.getFullYear()) * 12 - date1.getMonth() + date2.getMonth();
    var resM = monthCount % 12;
    var resY = parseInt(monthCount / 12);
    var resStr = "";
    if (resY != 0) {
      resStr += resY + "年"
    }
    if (resM != 0) {
      resStr += resM + "月"
    }
    if (resStr == "") {
      resStr = "0";
    }
    return resStr;
  }

</script>

<style scoped>
  .box{
    border:1px solid #E9EEF3;
    width:80%;
    height:100%;
    background: white;
    border-radius: 5px;
    box-shadow:#ccc 0px 0px 10px;
    margin:0 auto;

  }
  .info{
    color:#777;
    font-size:14px;
    border-left: 6px solid #409eff;
    width:80px;
    height:24px;
    text-align: center;
    margin-top: 15px;
    margin-left: 70px;

  }
  .empFrom >>> .el-form-item{
    margin-bottom: 0px;
  }

  .infoSpan{
    margin-left: 30px;
  }

  >>> .el-dialog__body{
    padding: 10px 20px;
  }
  >>> .distpicker-address-wrapper select{
    width: 80px;
  }
  .contentimg{
    margin-left: 49px;
    cursor: pointer;
  }
  .contentimg img{
    width: 150px;
    height: 150px;
    border-radius: 50%;
    overflow: hidden;
  }
  .contentimg .img_content{
    position: relative;
    padding: 0;
    width: 150px;
    height: 150px;
  }
  .contentimg .img_content .mask{
    position: absolute;
    top:-135px;
    left: 0;
    width: 150px;
    height: 150px;
    background: rgba(0,0,0,.2);
    color:#fff;
    font-size: 12px;
    border-radius: 50%;
    line-height: 147px;
    text-align: center;
    display: none;
  }
  .contentimg :hover .mask{
    display:block ;
  }
  /* 弹性布局 水平居中 */
  .show-preview {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }

  .preview {
    border-radius: 50%;
    overflow: hidden;
    border: 1px solid #cccccc;
    background: #cccccc;
  }

</style>
